<template>
  <div>
    <!-- 页面标题 -->
    <v-row class="mb-6">
      <v-col cols="12" md="6" class="d-flex justify-end align-center">
        <v-chip :color="timeColor" variant="elevated" class="me-3">
          {{ formattedTime }}
        </v-chip>
        <v-chip :color="restrictionColor" variant="outlined">
          {{ restrictionText }}
        </v-chip>
      </v-col>
    </v-row>




    <!-- 学生列表 -->
    <v-card>
      <v-card-title>
        {{ $t('teacher.student_departure_management') }}
        <v-spacer></v-spacer>
        <v-text-field
          v-model="searchText"
          append-inner-icon="mdi-magnify"
          :label="$t('teacher.search_student')"
          variant="filled"
          single-line
          hide-details
          density="compact"
          style="max-width: 300px;"
        ></v-text-field>
      </v-card-title>
      
      <v-card-text>
        <v-row>
          <v-col
            v-for="student in filteredStudents"
            :key="student.id"
            cols="12"
            sm="6"
            md="4"
            lg="3"
          >
            <DepartureStudentCard
              :student="student"
              :show-parent-info="true"
              @set-departure="(student) => openDepartureDialog(student, 'mark')"
              @set-abnormal="handleSetAbnormal"
              @edit-notes="handleEditNotes"
              @quick-update="handleQuickUpdate"
              @confirm-departure="(student) => openDepartureDialog(student, 'confirm')"
            />
          </v-col>
        </v-row>
        
        <div v-if="studentsStore.loading" class="text-center py-8">
          <v-progress-circular indeterminate color="primary"></v-progress-circular>
          <p class="mt-4">{{ $t('teacher.loading') }}</p>
        </div>
        
        <div v-if="!studentsStore.loading && filteredStudents.length === 0" class="text-center py-8">
          <v-icon size="64" color="grey">mdi-account-group-outline</v-icon>
          <p class="text-h6 mt-4">{{ $t('teacher.no_student_data') }}</p>
        </div>
        
        <!-- 分页组件 -->
         <div v-if="!studentsStore.loading && studentsStore.totalItems > itemsPerPage" class="d-flex justify-center mt-6">
           <v-pagination
             v-model="currentPage"
             :length="Math.ceil(studentsStore.totalItems / itemsPerPage)"
             :total-visible="7"
           ></v-pagination>
         </div>
      </v-card-text>
    </v-card>

    <!-- 离园状态更新对话框 -->
    <v-dialog v-model="departureDialog" max-width="500">
      <v-card>
        <v-card-title>
          {{ dialogMode === 'confirm' ? $t('teacher.confirm_student_departure') : dialogMode === 'notes' ? $t('teacher.edit_student_notes') : $t('teacher.mark_departure_status') }}
        </v-card-title>
        
        <v-card-text>
          <div class="text-center mb-4">
            <v-avatar size="64" :color="getAvatarColor(selectedStudent?.name || '')">
              <span class="text-h5 text-white">{{ selectedStudent?.name?.charAt(0) }}</span>
            </v-avatar>
            <h3 class="mt-2">{{ selectedStudent?.name }}</h3>
            <p class="text-caption">{{ selectedStudent?.student_no }}</p>
          </div>
          
          <!-- 标记模式：选择离园类型 -->
          <v-radio-group v-if="dialogMode === 'mark'" v-model="departureType" class="mb-4">
            <v-radio
              label="校车接送"
              value="bus"
              color="blue"
              :disabled="isBusRestricted"
            >
              <template v-slot:label>
                <div class="d-flex align-center">
                  <v-icon class="me-2" color="blue">mdi-bus-school</v-icon>
                  {{ $t('teacher.bus_pickup') }}
                  <v-chip
                    v-if="isBusRestricted"
                    size="x-small"
                    color="warning"
                    class="ms-2"
                  >
                    {{ $t('teacher.time_restriction') }}
                  </v-chip>
                </div>
              </template>
            </v-radio>
            
            <v-radio :label="$t('teacher.parent_pickup')" value="parent_pickup" color="green">
              <template v-slot:label>
                <div class="d-flex align-center">
                  <v-icon class="me-2" color="green">mdi-account-heart</v-icon>
                  {{ $t('teacher.parent_pickup') }}
                </div>
              </template>
            </v-radio>
            
            <v-radio :label="$t('teacher.after_school')" value="after_school" color="purple">
              <template v-slot:label>
                <div class="d-flex align-center">
                  <v-icon class="me-2" color="purple">mdi-school</v-icon>
                  {{ $t('teacher.after_school') }}
                </div>
              </template>
            </v-radio>
            
            <v-radio :label="$t('teacher.special_course')" value="special_course" color="orange">
              <template v-slot:label>
                <div class="d-flex align-center">
                  <v-icon class="me-2" color="orange">mdi-palette</v-icon>
                  {{ $t('teacher.special_course') }}
                </div>
              </template>
            </v-radio>
            

          </v-radio-group>
          
          <!-- 课后班级选择（仅当选择托班或特色课程时显示） -->
          <v-select
            v-if="dialogMode === 'mark' && (departureType === 'after_school' || departureType === 'special_course')"
            v-model="selectedAfterSchoolClass"
            :items="afterSchoolClasses"
            item-title="name"
            item-value="id"
            :label="$t('teacher.select_after_school_class')"
            variant="filled"
            density="comfortable"
            class="mb-4"
            :rules="[(v) => !!v || $t('teacher.please_select_class')]"
          >
            <template v-slot:item="{ props, item }">
              <v-list-item v-bind="props">
                <v-list-item-title>{{ item.raw.name }}</v-list-item-title>
                <v-list-item-subtitle v-if="item.raw.description">{{ item.raw.description }}</v-list-item-subtitle>
              </v-list-item>
            </template>
          </v-select>
          
          <!-- 备注编辑模式 -->
          <v-textarea
            v-if="dialogMode === 'notes'"
            v-model="departureNotes"
            :label="$t('teacher.student_notes')"
            variant="filled"
            rows="4"
            density="comfortable"
            :placeholder="$t('teacher.enter_notes')"
            class="mb-4"
          ></v-textarea>
          
          <!-- 确认模式：显示已标记的离园信息 -->
          <div v-if="dialogMode === 'confirm'" class="mb-4">
            <v-alert type="info" variant="tonal" class="mb-3">
              <v-alert-title>{{ $t('teacher.confirm_student_left_class') }}</v-alert-title>
              该学生已标记为{{ getDepartureMethodText(selectedStudent?.departure_method) }}，请确认学生是否已实际离班。
            </v-alert>
            
            <div class="d-flex align-center mb-3">
              <v-icon :color="getDepartureStatusColor(selectedStudent?.departure_status)" class="me-2">
                {{ getDepartureIcon(selectedStudent?.departure_status) }}
              </v-icon>
              <span class="text-h6">{{ getDepartureStatusText(selectedStudent?.departure_status) }}</span>
            </div>
            
            <div v-if="selectedStudent?.departure_marked_time" class="text-caption text-medium-emphasis mb-2">
              {{ $t('teacher.marked_time') }}: {{ selectedStudent.departure_marked_time }}
            </div>
          </div>
          
          <!-- 校车信息显示（仅标记模式） -->
          <v-alert
            v-if="!isConfirmMode && departureType === 'bus'"
            type="info"
            variant="tonal"
            class="mb-4"
          >
            <v-alert-title>校车信息</v-alert-title>
            学生将自动分配到已绑定的校车司机队列中
          </v-alert>
          
          <!-- 备注（仅标记模式） -->
          <v-textarea
            v-if="dialogMode === 'mark'"
            v-model="departureNotes"
            label="备注"
            variant="filled"
            rows="3"
            density="comfortable"
          ></v-textarea>
          
          <!-- 显示已有备注（确认模式） -->
          <div v-if="dialogMode === 'confirm' && selectedStudent?.notes" class="mb-3">
            <v-card variant="outlined">
              <v-card-text class="pa-3">
                <div class="text-caption text-medium-emphasis mb-1">备注信息:</div>
                <div class="text-body-2">{{ selectedStudent.notes }}</div>
              </v-card-text>
            </v-card>
          </div>
          
          <v-alert
            v-if="isBusRestricted && departureType === 'bus'"
            type="warning"
            variant="tonal"
            class="mt-3"
          >
            {{ attendanceSettings.modification_limit_time }}后，校车状态只能由司机修改！
          </v-alert>
        </v-card-text>
        
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="departureDialog = false">取消</v-btn>
          <v-btn
            v-if="dialogMode === 'mark'"
            color="primary"
            @click="confirmDepartureUpdate"
            :loading="updating"
            :disabled="!departureType || ((departureType === 'after_school' || departureType === 'special_course') && !selectedAfterSchoolClass)"
          >
            {{ $t('teacher.mark_departure') }}
          </v-btn>
          <v-btn
            v-else-if="dialogMode === 'confirm'"
            color="success"
            @click="confirmActualDeparture"
            :loading="updating"
          >
            {{ $t('teacher.confirm_departure') }}
          </v-btn>
          <v-btn
            v-else-if="dialogMode === 'notes'"
            color="primary"
            @click="confirmNotesUpdate"
            :loading="updating"
          >
            {{ $t('common.save') }}
          </v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useAuthStore } from '@/stores/auth'
import { useStudentsStore } from '@/stores/students'
import { useSocketStore } from '@/stores/socket'
import DepartureStudentCard from '@/components/DepartureStudentCard.vue'
import api from '@/utils/api'

const { t } = useI18n()

const authStore = useAuthStore()
const studentsStore = useStudentsStore()
const socketStore = useSocketStore()

// 响应式数据
const updating = ref(false)
const searchText = ref('')
const departureDialog = ref(false)
const selectedStudent = ref(null)
const departureType = ref('')
const departureNotes = ref('')
const selectedAfterSchoolClass = ref('')
const afterSchoolClasses = ref([])
const dialogMode = ref('mark') // 对话框模式：mark, confirm, notes
// 移除校车选择相关变量，现在使用学生绑定的校车

// 分页相关数据
const currentPage = ref(1)
const itemsPerPage = ref(10) // 每页显示10个学生卡片
const attendanceSettings = ref({
  modification_limit_time: '14:00'
})

// 计算属性
const formattedTime = computed(() => {
  return new Date().toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  })
})

const timeColor = computed(() => {
  const hour = new Date().getHours()
  const limitTime = attendanceSettings.value.modification_limit_time
  const [limitHour] = limitTime.split(':').map(Number)
  if (hour < limitHour) return 'green'
  if (hour < 17) return 'orange'
  return 'red'
})

const isBusRestricted = computed(() => {
  const limitTime = attendanceSettings.value.modification_limit_time
  const [limitHour] = limitTime.split(':').map(Number)
  return new Date().getHours() >= limitHour && authStore.userRole === 'teacher'
})

const restrictionColor = computed(() => {
  return isBusRestricted.value ? 'warning' : 'success'
})

const restrictionText = computed(() => {
  return isBusRestricted.value ? '校车限制时间' : '正常操作时间'
})



const filteredStudents = computed(() => {
  // 使用store中的学生数据
  return studentsStore.students
})

// 移除校车选项计算属性，现在使用学生绑定的校车

const departureStats = computed(() => {
  return studentsStore.students.reduce((acc, student) => {
    const status = student.departure_status || 'not_left'
    acc[status] = (acc[status] || 0) + 1
    return acc
  }, {
    bus: 0,
    parent_pickup: 0,
    after_school: 0,
    special_course: 0,
    abnormal: 0,
    not_left: 0
  })
})

const hasBusStudents = computed(() => {
  return departureStats.value.bus > 0
})

// 方法
// 加载考勤设置
const loadAttendanceSettings = async () => {
  try {
    const response = await api.get('/settings/attendance')
    if (response.data.success) {
      const data = response.data.data
      attendanceSettings.value = {
        modification_limit_time: data.modification_limit_time?.value?.substring(0, 5) || '14:00'
      }
    }
  } catch (error) {
    console.error('加载考勤设置失败:', error)
    // 使用默认值，不显示错误提示
  }
}

const loadStudents = async () => {
  try {
    // 使用WebSocket获取班级考勤信息
    socketStore.socket.emit('get-class-attendance', {
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole,
      date: new Date().toISOString().split('T')[0],
      page: currentPage.value,
      limit: itemsPerPage.value,
      search: searchText.value || undefined
    })
  } catch (error) {
    console.error('加载学生列表失败:', error)
    window.showNotification?.('加载学生列表失败', 'error')
  }
}

// 加载课后班级列表
const loadAfterSchoolClasses = async () => {
  try {
    const response = await api.get('/after-school/classes')
    if (response.data.success) {
      afterSchoolClasses.value = response.data.data.classes || []
    }
  } catch (error) {
    console.error(t('teacher.load_after_school_classes_failed'), error)
  }
}

// 移除加载校车列表方法，现在使用学生绑定的校车

const openDepartureDialog = (student, mode = 'mark') => {
  selectedStudent.value = student
  dialogMode.value = mode
  
  if (mode === 'mark') {
    // 标记模式：重置表单
    departureType.value = ''
    departureNotes.value = ''
    selectedAfterSchoolClass.value = ''
  } else if (mode === 'confirm') {
    // 确认模式：显示已标记的信息
    departureType.value = student.departure_method || ''
  }
  
  departureDialog.value = true
}

const handleQuickUpdate = async (data) => {
  const { student, departureType: type, notes } = data
  
  try {
    updating.value = true
    
    // 使用WebSocket更新学生离园状态
    socketStore.socket.emit('update-student-departure', {
      studentId: student.id,
      departureType: type,
      notes: notes || '',
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole
    })
    
  } catch (error) {
    console.error(t('teacher.mark_departure_failed'), error)
    window.showNotification?.(t('teacher.quick_mark_failed'), 'error')
    updating.value = false
  }
}



const confirmDepartureUpdate = async () => {
  updating.value = true
  try {
    // 使用WebSocket更新学生离园状态
    socketStore.socket.emit('update-student-departure', {
      studentId: selectedStudent.value.id,
      departureType: departureType.value,
      notes: departureNotes.value,
      afterSchoolClassId: (departureType.value === 'after_school' || departureType.value === 'special_course') ? selectedAfterSchoolClass.value : null,
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole
    })
    
    departureDialog.value = false
    
  } catch (error) {
    console.error(t('teacher.mark_departure_failed'), error)
    window.showNotification?.(t('teacher.departure_update_failed'), 'error')
    updating.value = false
  }
}

// 确认学生实际离校
const confirmActualDeparture = async () => {
  updating.value = true
  try {
    // 使用WebSocket确认学生离校
    socketStore.socket.emit('confirm-student-departure', {
      studentId: selectedStudent.value.id,
      teacherId: authStore.user.id, // 修正为user.id
      userRole: authStore.userRole
    })
    
    departureDialog.value = false
    
  } catch (error) {
    console.error('确认学生离班失败:', error)
    window.showNotification?.('确认学生离班失败', 'error')
    updating.value = false
  } finally {
    updating.value = false
  }
}

// 设置学生异常状态
const handleSetAbnormal = async (student) => {
  try {
    // 使用WebSocket设置学生异常状态
    socketStore.socket.emit('set-student-abnormal', {
      studentId: student.id,
      teacherId: authStore.user.id,
      userRole: authStore.userRole
    })
    
    window.showNotification?.('已设置学生异常状态', 'success')
    
  } catch (error) {
    console.error('设置异常状态失败:', error)
    window.showNotification?.('设置异常状态失败', 'error')
  }
}

// 编辑学生备注
const handleEditNotes = (student) => {
  selectedStudent.value = student
  departureNotes.value = student.notes || ''
  // 打开备注编辑对话框
  departureDialog.value = true
  dialogMode.value = 'notes'
}

// 确认备注更新
const confirmNotesUpdate = async () => {
  updating.value = true
  try {
    // 使用WebSocket更新学生备注
    socketStore.socket.emit('update-student-notes', {
      studentId: selectedStudent.value.id,
      notes: departureNotes.value,
      teacherId: authStore.user.id,
      userRole: authStore.userRole
    })
    
    departureDialog.value = false
    window.showNotification?.('备注更新成功', 'success')
    
  } catch (error) {
    console.error('更新备注失败:', error)
    window.showNotification?.('更新备注失败', 'error')
  } finally {
    updating.value = false
  }
}



const getAvatarColor = (name) => {
  const colors = ['primary', 'secondary', 'accent', 'info', 'success']
  const index = name.charCodeAt(0) % colors.length
  return colors[index]
}

const getArrivalStatusColor = (status) => {
  const colorMap = {
    present: 'green',
    leave: 'orange',
    abnormal: 'red'
  }
  return colorMap[status] || 'grey'
}

const getArrivalStatusText = (status) => {
  const textMap = {
    present: '已到',
    leave: '请假',
    abnormal: '异常'
  }
  return textMap[status] || '未到'
}

const getDepartureStatusColor = (status) => {
  const colorMap = {
    bus: 'blue',
    parent_pickup: 'green',
    after_school: 'purple',
    special_course: 'orange',
    abnormal: 'red',
    not_left: 'grey'
  }
  return colorMap[status] || 'grey'
}

const getDepartureStatusText = (status) => {
  const textMap = {
    bus: '校车',
    parent_pickup: '家长接领',
    after_school: '晚托班',
    special_course: '特色课程',
    abnormal: '异常',
    not_left: '未离园'
  }
  return textMap[status] || '未离园'
}

const getDepartureIcon = (status) => {
  const iconMap = {
    bus: 'mdi-bus-school',
    parent_pickup: 'mdi-account-heart',
    after_school: 'mdi-school',
    special_course: 'mdi-palette',
    abnormal: 'mdi-alert',
    not_left: 'mdi-home-outline'
  }
  return iconMap[status] || 'mdi-home-outline'
}

const getDepartureMethodText = (method) => {
  const textMap = {
    bus: '校车',
    parent_pickup: '家长接领',
    after_school: '晚托班',
    special_course: '特色课程'
  }
  return textMap[method] || '未设置'
}

// 监听器
watch(currentPage, () => {
  loadStudents()
})

// 防抖搜索
let searchTimeout = null
watch(searchText, () => {
  if (searchTimeout) clearTimeout(searchTimeout)
  searchTimeout = setTimeout(() => {
    currentPage.value = 1 // 搜索时重置到第一页
    loadStudents()
  }, 500)
})

// WebSocket事件监听器
const setupSocketListeners = () => {
  if (!socketStore.socket) return
  
  // 监听班级考勤数据响应
  socketStore.socket.on('class-attendance-data', (response) => {
    if (response.success) {
      studentsStore.students = response.data.students || []
      studentsStore.totalItems = response.data.total || 0
    } else {
      console.error('获取班级考勤数据失败:', response.message)
      window.showNotification?.(response.message || '获取班级考勤数据失败', 'error')
    }
  })
  
  // 监听学生离园状态更新响应
  socketStore.socket.on('student-departure-updated', (response) => {
    updating.value = false
    if (response.success) {
      window.showNotification?.('离园状态更新成功', 'success')
      // 刷新学生列表
      loadStudents()
    } else {
      window.showNotification?.(response.message || '更新离园状态失败', 'error')
    }
  })
  
  // 监听学生离班确认响应
  socketStore.socket.on('student-departure-confirmed', (response) => {
    updating.value = false
    if (response.success) {
      window.showNotification?.('学生离班确认成功', 'success')
      // 刷新学生列表
      loadStudents()
    } else {
      window.showNotification?.(response.message || '确认学生离班失败', 'error')
    }
  })
  
  // 监听学生状态实时更新
  socketStore.socket.on('student-status-updated', (data) => {
    // 实时更新学生列表
    loadStudents()
  })
}

// 清理WebSocket监听器
const cleanupSocketListeners = () => {
  if (!socketStore.socket) return
  
  socketStore.socket.off('class-attendance-data')
  socketStore.socket.off('student-departure-updated')
  socketStore.socket.off('student-departure-confirmed')
  socketStore.socket.off('student-status-updated')
}

// 生命周期
onMounted(() => {
  setupSocketListeners()
  // 加载考勤设置和教师班级的学生信息
  loadAttendanceSettings()
  loadStudents()
  loadAfterSchoolClasses()
})

onUnmounted(() => {
  cleanupSocketListeners()
})
</script>

<style scoped>
.v-data-table {
  border-radius: 8px;
}

.departure-stats {
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  border-radius: 8px;
  padding: 16px;
}

.stat-item {
  transition: transform 0.2s ease;
}

.stat-item:hover {
  transform: scale(1.05);
}

.color-sample {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  display: inline-block;
}

.color-sample.status-departed {
  background: linear-gradient(135deg, #4CAF50, #66BB6A);
}

.color-sample.status-abnormal {
  background: linear-gradient(135deg, #F44336, #EF5350);
}

.color-sample.status-waiting {
  background: linear-gradient(135deg, #9E9E9E, #BDBDBD);
}
</style>
